library(ggplot2)
library(cluster) # silhouette()
wine <- read.csv("https://greymonroe.github.io/PLS_206/data/winedata.csv")
chem <- wine[, -1] # the 13 chemical columns (drop Cultivar)
X <- scale(chem) # each chemical scaled to mean 0, SD 1Problem Set 8: Clustering
PLS 206 — Applied Multivariate Modeling
Due: Monday, November 23, 1:10 PM (start of class) — submitted through Canvas.
Questions 1–4 use Monday’s lecture (k-means, the elbow, silhouette). Questions 5–7 use Wednesday’s (distance matrices, hierarchical clustering, linkage, cutree()). Monday’s live script Week8_live_1_kmeans.R and Wednesday’s live script Week8_live_2_hclust.R have working code for every step.
Stuck? Every question has a hint. Open it: most hints contain a code skeleton where you only fill in the blanks (___) and say what your output should look like.
Submission Instructions
Upload two files to Canvas:
- Written answers — a
.pdfdocument with your written responses, interpretations, and figures. - R script — a
.Rfile with all the code you used to produce your answers.
List the first and last names of any collaborators in both files.
Naming convention: HW8emailID.R (code) and HW8emailID.pdf (written answers), where emailID is the part of your UC Davis email before the @.
Example: Grey Monroe would submit
HW8gmonroe.RandHW8gmonroe.pdf.
Feel free to use Google, StackOverflow, and other resources if you are stuck with code, and post questions on Slack if anything is unclear.
The data
Wine. The wine data from Problem Set 7: 13 chemical measurements on 178 wines from three cultivars (barbera, barolo, gringnolino). This week we hide the cultivar labels from the methods and ask: can clustering find the three cultivars from the chemistry alone? Because we know the answer, we can check how well each method does. On real data you rarely get that luxury.
Cluster numbers are arbitrary labels. k-means and cutree() call the groups 1, 2, 3, but which group gets which number is an accident of the algorithm (and of the random seed). Cluster 1 is not “the first cultivar”. To compare clusters with cultivars, cross-tabulate them with table() and match each cluster to the cultivar it mostly contains. When the match is good, each row of the table has one big number and two small ones.
Percent agreement. This helper does the matching for you: it tries every way of pairing the 3 clusters with 3 groups and returns the share of wines that land in their matched group. Paste it into your script and use it whenever a question asks for agreement.
agreement <- function(a, b) {
tab <- table(a, b) # 3 x 3 cross-tabulation
perms <- list(c(1, 2, 3), c(1, 3, 2), c(2, 1, 3),
c(2, 3, 1), c(3, 1, 2), c(3, 2, 1)) # every way to pair them up
max(sapply(perms, function(p) sum(diag(tab[, p])))) / length(a)
}The pieces of a clustering in R:
| You want | In R | One number per |
|---|---|---|
| each wine’s k-means cluster | km$cluster |
wine |
| k-means cluster centres (means of each variable) | km$centers |
cluster × variable |
| total within-cluster sum of squares | km$tot.withinss |
fit |
| distance between every pair of wines | dist(X) |
pair of wines |
| each wine’s hierarchical cluster | cutree(h, k = 3) |
wine |
| each wine’s silhouette width | silhouette(clusters, d)[, "sil_width"] |
wine |
Seeds. k-means starts from random centres, so put set.seed(206) right before every kmeans() call. With nstart = 25 your clusters should match a classmate’s up to the arbitrary numbering.
Part 1: k-means
Q1. Does scaling matter? Run k-means with 3 clusters (nstart = 25) twice: on the raw chemicals (chem) and on the scaled chemicals (X). Show the cross-tabulation of clusters against cultivar for each, and report the percent agreement. Explain in two sentences why the unscaled version does worse. (Think about what k-means measures, and look back at PS7 Q1.)
set.seed(206)
km_raw <- kmeans(chem, centers = 3, nstart = 25) # unscaled
table(km_raw$cluster, wine$Cultivar)
agreement(km_raw$cluster, wine$Cultivar) # share between 0 and 1
set.seed(206)
km <- kmeans(___, centers = 3, nstart = 25) # scaled
table(km$cluster, wine$Cultivar)
agreement(km$cluster, wine$Cultivar)Each table has clusters as rows and cultivars as columns; a good fit has one big number per row. k-means puts each wine in the cluster with the nearest centre, using Euclidean distance. Which chemical contributes the biggest differences to that distance when nothing is scaled? sapply(chem, var) will remind you. Slides Unscaled: the big numbers win and Scale first: every variable SD 1 (Monday).
Q2. Pretend you did not know there were three cultivars. On the scaled data, compute the total within-cluster sum of squares for k = 1 to 10 (the elbow plot) and the average silhouette width for k = 2 to 10. Show both plots. What k does each suggest?
wss <- sapply(1:10, function(k) {
set.seed(206)
kmeans(X, centers = k, nstart = 25)$tot.withinss
})
plot(1:10, wss, type = "b", xlab = "k", ylab = "Total within-cluster SS")
d <- dist(X) # distances between all pairs of wines
sil <- sapply(2:10, function(k) {
set.seed(206)
cl <- kmeans(X, centers = k, nstart = 25)$cluster
mean(silhouette(cl, d)[, "sil_width"]) # average silhouette width
})
plot(___, sil, type = "b", xlab = "k", ylab = "Average silhouette width") # sil has 9 values: k = 2 to 10The sum of squares always falls as k grows (more centres, shorter distances), so look for where it stops falling steeply. For the silhouette, look for the highest point. Values range from −1 to 1. Slides Elbow: where more clusters stop paying and Average silhouette: pick the highest (Monday).
Q3. Using the k from Q2 and the scaled k-means fit, plot the wines on PC1 and PC2 (as in PS7), coloured by k-means cluster and shaped by cultivar. Report the cross-tabulation and percent agreement in words: how many wines did k-means put with the “wrong” cultivar, which cultivars do they come from, and where do they sit on the plot?
# km = your scaled k-means fit from Q1 (refit it with your k if Q2 pointed somewhere else)
pca <- prcomp(chem, scale. = TRUE)
scores <- data.frame(pca$x[, 1:2],
Cluster = factor(km$cluster),
Cultivar = wine$Cultivar)
ggplot(scores, aes(PC1, PC2, colour = ___, shape = ___)) +
geom_point(size = 2) +
coord_fixed() +
theme_classic()
table(km$cluster, wine$Cultivar)
agreement(km$cluster, wine$Cultivar) # share between 0 and 1Read the table row by row: match each cluster to the cultivar with the big number, and the small numbers in that row are the mismatches. On the plot, mismatches are points whose shape belongs to one cloud but whose colour belongs to another. Are they in the middle of a cloud or at an edge between two? Slides Cluster numbers are just names and In R: compare with table() (Monday).
Q4. What makes each cluster different? Print the k-means cluster centres (km$centers, in SD units because the data were scaled). For each cluster, name the two or three chemicals furthest from zero and describe the cluster in a sentence of plain chemistry. Which cultivar is each?
round(km$centers, 2) # 3 rows (clusters) x 13 columns (chemicals), in SD units
table(km$cluster, wine$Cultivar) # from Q1: which cultivar fills each clusterA centre of +1.1 for Proline means the wines in that cluster average 1.1 SD above the overall mean in proline. Look for the biggest positive and negative numbers in each row. Compare with your PS7 description of PC1 and PC2: the same chemicals should come up.
Part 2: Hierarchical Clustering
Q5. Build a hierarchical clustering of the scaled wines (dist(X)) with three linkages: "complete", "ward.D2", and "single". Cut each tree into 3 clusters with cutree(). For each linkage report the cluster sizes and the percent agreement with cultivar. One linkage fails badly: say which, and explain from how it defines the distance between two clusters why it fails.
d <- dist(X)
h_complete <- hclust(d, method = "complete")
h_ward <- hclust(d, method = "___")
h_single <- hclust(d, method = "___")
cl_complete <- cutree(h_complete, k = 3)
table(cl_complete) # cluster sizes
agreement(cl_complete, wine$Cultivar)
# ...same for ward and singleSingle linkage joins two clusters by their closest pair of points, complete linkage by their farthest pair, and Ward’s method joins the pair that adds the least within-cluster sum of squares (the same quantity k-means minimises). If the sizes come out as one huge cluster and two tiny ones (a handful of wines or fewer), the method is peeling off a few outlying wines and chaining everything else into one group. Slides Complete: compares the farthest points, Single: compares the closest points and Complete linkage: one blob and a few stragglers (Wednesday).
Q6. Plot the Ward dendrogram with each leaf labelled by its cultivar and boxes around the 3 clusters from cutree(). Does the shape of the tree support three groups? At about what height would you cut it, and would cutting at 2 or 4 groups also look reasonable from the tree alone?
plot(h_ward, labels = substr(wine$Cultivar, 1, 4), cex = 0.35,
main = "Ward linkage, scaled wine chemistry", xlab = "", sub = "")
rect.hclust(h_ward, k = ___) # boxes around the clustersThe height of a merge is how far apart the two groups were when they were joined. A natural number of clusters shows up as a few long vertical branches: a big jump in height before the last few merges. rev(h_ward$height)[1:5] lists the heights of the last five merges, tallest first. Slide cutree(): cut at any K (Wednesday).
Q7. Compare k-means (Q3) with Ward hierarchical clustering (Q5) directly: cross-tabulate their clusters and report their percent agreement with each other. Which of the two matches the cultivars better? Give one reason the two methods can disagree on the same data.
cl_ward <- cutree(h_ward, k = 3)
table(km$cluster, cl_ward)
agreement(km$cluster, ___)agreement() works for any two sets of 3 labels, not only cultivars. A good match has one big number per row, as in Q1. Think about what happens to a wine once hierarchical clustering has merged it into a group early on, and whether k-means can move a wine later. Slides Colombia: k-means vs hierarchical and k-means or hierarchical? (Wednesday).
Part 3: Clusters Without Answers
Q8. Clustering always returns clusters, even when there are none. Simulate 178 “wines” with 13 independent, normally distributed chemicals (pure noise), run k-means with k = 3, and report the cluster sizes and the average silhouette width. Compare it with the average silhouette for the real wines at k = 3 from Q2. What does this tell you about reading cluster results?
set.seed(206)
noise <- matrix(rnorm(178 * 13), ncol = 13) # no structure at all
km_noise <- kmeans(noise, centers = 3, nstart = 25)
km_noise$size # three groups of similar size
mean(silhouette(km_noise$cluster, dist(___))[, "sil_width"])k-means will happily cut a structureless cloud into 3 pieces of similar size. The silhouette asks whether wines are much closer to their own cluster than to the next one. A common rule of thumb reads an average width below about 0.25 as no substantial structure. Your Q2 sil vector holds the real-wine value: sil[2] is k = 3. Slide k-means always finds k clusters (Monday).
Q9. In this problem set we could check every answer against the known cultivars. Suppose instead you clustered 200 unlabelled cassava landraces on 13 traits. In three to five sentences, say what you would do to convince yourself (and a reviewer) that the clusters are real and worth naming. Use at least two things you learned in this problem set.
There is no single right answer. Think about: scaling and the choice of variables, more than one way of choosing k, more than one method (do they agree?), comparing with a structureless baseline (Q8), and whether the cluster centres tell a story that makes biological sense (Q4). Slides Choosing k: no single right answer (Monday) and Check clusters against what you know (Wednesday).